<template>
  <div class="container">
    <div class="sidebar">
      <p style="text-align: center">
        <el-button type="primary" @click="save">新增分组</el-button>
        <el-button type="success" @click="updated">修改分组</el-button>
        <el-button type="warning" @click="deleteById">批量删除</el-button>
      </p>
      <el-tree
          ref="tree"
          :data="data"
          show-checkbox
          node-key="categoryId"
          :props="{ label: 'categoryName', children: 'sonList' }"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          @check-change="handleCheck"
          default-expand-all
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
              type="text"
              size="mini"
              @click="() => remove(data)">
            删除
          </el-button>
        </span>
      </span>
      </el-tree>
      <el-dialog
          title="分组信息"
          :visible.sync="dialogFormVisible"
          width="450px"
      >
        <el-form :model="category" style="width: 250px">
          <el-form-item label="分组名字" size="small">
            <el-input
                v-model="category.categoryName"
                autocomplete="on"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="false" label="选择所属" size="small">
            <el-cascader
                v-model="category.parentId"
                style="width: 160px"
                size="medium"
                :options="data"

                @change="categoryChange"
                :props="{
              label: 'categoryName',
              value: 'categoryId',
              children: 'sonList',
              emitPath: false
            }"
                clearable
                filterable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="排序" size="small" style="width: 160px">
            <el-input v-model="category.sortOrder" autocomplete="on"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
                v-model="category.description"
                autocomplete="on"
                row="20"
                :style="{ width: '400px', height: '5px' }"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <span>父级分类</span>
            <el-cascader
                v-model="category.parentId"
                style="width: 160px"
                size="medium"
                :options="data"
                :props="{
            checkStrictly: true,
            label: 'categoryName',
            value: 'categoryId',
            children: 'sonList',
            emitPath: false,
          }"
                clearable
                filterable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="content">
      <el-table :data="product" border style="width: 100%" :default-sort="{prop: 'updateTime', order: 'descending'}">
        <el-table-column prop="name" label="商品名" width="180">
        </el-table-column>
        <el-table-column sortable prop="price" label="单价(元)" :formatter="rounding">
        </el-table-column>
        <el-table-column prop="image" label="照片">
          <template slot-scope="scope">
            <img :src="scope.row.image" width="80"/>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <template v-if="scope.row.status === 0"> 充足</template>
            <template v-else-if="scope.row.status === 1"> 待补货</template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json
import http from "../utils/request";
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      //被点击的节点
      product: '',
      nodeId: 0,
      diaType: "",
      dialogFormVisible: false,
      data: [],
      ids: [],
      productLimit: 10,
      productPage: 1,
      category: {
        categoryName: "",
        categoryId: "",
        parentId: "",
        description: "",
        sortOrder: 0,
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    submit() {
      if (this.diaType === "save") {
        this.saveThis();
      } else {
        this.update();
      }
    },
    update() {
      this.$confirm("更新操作无法撤销，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.category.categoryId = this.nodeId;
            http.put("/category/update", this.category).then(({data}) => {
              console.info("返回数据", data);
              if (data.code == 1) {
                //这里加一个提示框
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                console.info("保存成功");
                this.getCatgoryPage();
                this.dialogFormVisible = false;
                this.category.categoryName = "";
                this.category.categoryId = "";
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消更新",
            });
          });
    },
    saveThis() {
      http.post("/category/save", this.category).then(({data}) => {
        console.info("返回数据", data);
        if (data.code == 1) {
          //这里加一个提示框
          this.$message({
            type: "success",
            message: "保存成功!",
          });
          console.info("保存成功");
          this.getCatgoryPage();
          this.dialogFormVisible = false;

        }
      });
    },
    save() {
      this.category = {
        categoryName: "",
        categoryId: "",
        parentId: "",
        description: "",
        sortOrder: 0,
      };
      if (this.category.parentId == "" && this.data === []) {
        this.$message.error("请先点击分类父节点");
        return;
      }
      this.diaType = "save";
      this.dialogFormVisible = true;

      console.log("要新增父节点id", this.nodeId);
      this.nodeId = 0;
    },
    updated() {
      if (this.nodeId == 0) {
        this.$message.error("点击需要修改的分类");
      } else {
        this.diaType = "update";
        http.get(`/category/get/${this.nodeId}`).then(({data}) => {
          console.info("接收到分组数据", data.data);
          this.category.categoryName = data.data.categoryName;
          this.category.description = data.data.description;
          this.category.parentId = data.data.parentId;
          this.category.sortOrder = data.data.sortOrder;
        });
        this.dialogFormVisible = true;
        console.log("要修改的数据是", this.nodeId);
      }
    },
    remove(data) {
      console.log(data,this.ids);
      this.ids.push(data.categoryId);
      this.deleteById()
    },
    deleteById() {
      console.log("要删除的数据是", this.ids);
      if (this.ids.length === 0) {
        this.$message.error("请先选择要删除的分组");
      } else {
        this.sure();
      }
    },
    sure() {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            http.delete(`/category/delete/${this.ids}`).then(({data}) => {
              if (data.code === 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.getCatgoryPage();
              } else {
                this.$message.error("删除失败");
              }
            }).catch(() => {
              this.$message.error("该分类不为空，无法删除");
            }).finally(() => {
              this.ids = "";
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
    },

    handleCheck(node) {
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      this.ids = checkedNodes.map((node) => node.categoryId);
    },
    treeitem(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].sonList.length < 1) {
          data[i].sonList = undefined;
        } else {
          this.treeitem(data[i].sonList);
        }
      }
      return data;
    },

    getCatgoryPage() {
      http.get("/category/tree", "").then(({data}) => {
        console.info("接收到分组数据", data.data);
        this.data = this.treeitem(data.data);
      });
    },
    handleNodeClick(node) {
      console.log("点击节点", node);
      // 处理节点点击事件
      this.nodeId = node.categoryId;
      this.category.parentId = node.categoryId;
      http
          .get(
              `/product/list?categoryId=${this.nodeId}&page=${this.productPage}&limit=${this.productLimit}`
          )
          .then(({data}) => {
            console.info("接收到传入数据", data.data);
            this.product = data.data.records;
            console.info("接收到解析数据", this.product);
          });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getCatgoryPage();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
  },
  beforeCreate() {
  }, //生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
  }, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.container {
  display: flex;
  height: 100vh;
}

.sidebar {
  flex: 4;
  background-color: #f0f0f0;
  padding: 5px;
}

.content {
  flex: 6;
  padding: 5px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
